package com.yt.base.controller.base;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.google.common.base.Strings;
import com.yt.base.controller.core.BaseController;
import com.yt.base.model.AclCategory;
import com.yt.base.model.AclOperation;
import com.yt.base.service.AclGroupOperationService;
import com.yt.base.service.AclGroupService;
import com.yt.core.MsgBean;
import com.yt.core.dao.PagingBean;
import com.yt.core.dao.filter.DynamicSQLFilterImpl;
import com.yt.core.dao.filter.QueryFilter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.yt.base.model.AclGroupOperation;
import com.yt.base.model.AclPrivilege;
import com.yt.base.model.AclGroup;
import com.yt.base.service.AclCategoryService;
import com.yt.base.service.AclOperationService;
import com.yt.base.service.AclPrivilegeService;
import com.yt.base.service.AclUserService;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

@Controller
@RequestMapping("/base/group")
public class GroupAclController extends BaseController {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private AclGroupService groupService;
	@Autowired
	private AclUserService userService;
	@Autowired
	private AclCategoryService catService;
	@Autowired
	private AclPrivilegeService privService;
	@Autowired
	private AclOperationService opService;
	@Autowired
	private AclGroupOperationService groupOpService;

	@RequestMapping({"/toPermission"})
	public ModelAndView toPermission(@RequestParam("groupId") Long groupId, HttpServletRequest request) {
		logger.debug("查询组权限：groupId={}", groupId);
		ModelAndView mav = new ModelAndView("base/group/GroupPermission");

		AclGroup group = groupService.get(groupId);
		if (group == null) {
			throw new RuntimeException("查询的组不存在");
		}
		mav.addObject("group", group);

		List<AclCategory> categoryList = catService.findAll();
		List<AclPrivilege> privilegeList = privService.findAll();
		List<AclOperation> operationList = opService.findAll();

		mav.addObject("categoryList", categoryList);
		mav.addObject("privilegeList", privilegeList);
		mav.addObject("operationList", operationList);

		List<String> keyList = Lists.newArrayList();
		List<AclGroupOperation> groupOpList = groupOpService.findByGroup(groupId);
		for (AclGroupOperation op : groupOpList) {
			StringBuilder sb = new StringBuilder().append(op.getCategoryId()).append("_").append(op.getPrivilegeId()).append("_").append(op.getOperationId());
			keyList.add(sb.toString());
		}
		mav.addObject("keyList", keyList);
		return mav;
	}

	@RequestMapping("/saveAcl")
	public
	@ResponseBody
	Object saveAcl(@RequestParam("aclist") String aclist, @RequestParam("groupId") Long groupId) {
		logger.debug("更新用户组[{}]权限", groupId);

		MsgBean msg = new MsgBean();

		AclGroup group = groupService.get(groupId);
		if (group == null) {
			msg.setFailure("1", "用户组不存在");
		} else if (StringUtils.isEmpty(aclist.trim())) {
			msg.setFailure("1", "权限集合不可为空");
		} else {
			List<String> aclList = Splitter.on(',').trimResults().splitToList(aclist);
			groupOpService.modify(group, aclList);
		}
		return msg.returnMsg();
	}

	@RequestMapping({"/list"})
	public ModelAndView list(@RequestParam(value = "start", required = false) String start, @RequestParam(value = "limit", required = false) String limit, @RequestParam(value = "pageNo", required = false) Integer pageNo, HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("base/group/GroupList");

		PagingBean page = new PagingBean();
		int currentPage = 0;
		int pageSize = 25;
		if (StringUtils.isNotEmpty(limit) && StringUtils.isNumeric(limit)) {
			pageSize = Integer.parseInt(limit);
		}
		if (StringUtils.isNotEmpty(start) && StringUtils.isNumeric(start)) {
			currentPage = (Integer.parseInt(start) - 1) * pageSize;
		}

		page.setPageSize(pageSize);
		page.setStart(currentPage);

		QueryFilter filter = new DynamicSQLFilterImpl();
		filter.setPagingBean(page);
		filter.setSortField("id", true);
		List<AclGroup> groupList = groupService.find(filter);
		int groupCount = groupService.count(filter);
		mav.addObject("total", groupCount);
		mav.addObject("start", start);
		mav.addObject("limit", limit);
		mav.addObject("groupList", groupList);
		return mav;
	}

	@RequestMapping(value = "/toAdd")
	public ModelAndView toAdd(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("base/group/GroupAdd");
		String id = request.getParameter("id");
		if (StringUtils.isNotEmpty(id)) {
			AclGroup group = groupService.get(Long.parseLong(id));
			mav.addObject("editingGroup", group);
		}
		return mav;
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public
	@ResponseBody
	Object save(@RequestParam(value = "groupId", required = false) String groupId, @RequestParam("groupName") String groupName, HttpServletRequest request) {
		logger.debug("添加组：" + groupName);
		MsgBean msg = new MsgBean();
		try {
			AclGroup oldGroup = groupService.findByName(groupName);
			//修改操作
			if (StringUtils.isNotEmpty(groupId) && StringUtils.isNumeric(groupId)) {
				AclGroup dbGroup = groupService.get(Long.parseLong(groupId));
				if (oldGroup == null || oldGroup.getId() == dbGroup.getId()) {
					dbGroup.setName(groupName);
					groupService.update(dbGroup);
				} else {
					msg.setFailure(1, "组名已经存在");
					return msg.returnMsg();
				}
			} else {
				if (oldGroup == null) {
					AclGroup group = new AclGroup(groupName);
					groupService.insert(group);
				} else {
					msg.setFailure(1, "组名已经存在");
					return msg.returnMsg();
				}
			}
		} catch (Exception e) {
			logger.error("添加组出错：{}", e.getMessage(), e);
		}
		return msg.returnMsg();
	}

	@RequestMapping("/search")
	public
	@ResponseBody
	Object search(@RequestParam("name") String name) {
		MsgBean msg = new MsgBean();

		if (Strings.isNullOrEmpty(name)) {
			msg.setFailure("查询条件不可为空!");
		}
		return msg.returnMsg();
	}

	@RequestMapping("/toModify")
	public ModelAndView toModify(@RequestParam("groupId") Long groupId, HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("base/group/GroupAdd");
		AclGroup group = groupService.get(groupId);
		mav.addObject("editingGroup", group);
		mav.addObject("action", "modify");
		return mav;
	}

	@RequestMapping("/del")
	public
	@ResponseBody
	Object delete(@RequestParam("groupId") Long groupId) {
		MsgBean msg = new MsgBean();

		AclGroup group = groupService.get(groupId);
		if (group != null) {
			logger.warn("操作者[{}]将要删除组[{}]", "", group.getName());

			int memNum = userService.countByGroup(groupId);
			if (memNum > 0) {
				msg.setFailure(1, "非空组不可以删除");
			} else {
				groupService.remove(groupId);
			}
		}

		return msg.returnMsg();
	}
}
